/**
 *
 */
package com.rf.richfitwheel.admin.sys.controller;


import com.rf.richfitwheel.admin.annotation.ModifyAnnotaionFactory;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.sys.model.Dictionary;
import com.rf.richfitwheel.admin.sys.model.Org;
import com.rf.richfitwheel.admin.sys.model.Station;
import com.rf.richfitwheel.admin.sys.service.OrgService;
import com.rf.richfitwheel.admin.sys.service.StationService;
import com.rf.richfitwheel.admin.sys.service.SysDicService;
import com.rf.richfitwheel.admin.sys.service.SysMenuService;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.CommonServiceError;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.TreeUtils;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 岗位管理
 * @author hushouquan
 *
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/station")
public class SysStationController {

    private static Logger log = LoggerFactory.getLogger(SysStationController.class);

    @Autowired
    private StationService stationService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private OrgService orgService;

    @Autowired
    private SysDicService sysDicService;

    /**
     * 岗位分页查询
     * @param page
     * @param limit
     * @param dataForm
     * @return
     */
    @GetMapping("/queryList")
    public R queryList(String page, String limit, String dataForm, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        params.put("limit", limit);
        params.put("dataForm", dataForm);
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
        params.put("moduleTypeHead", moduleType);
        try {
            PageUtils pages = stationService.queryPage(params);
            return R.ok().put("page", pages);
        } catch (IOException e) {
            log.error("无法解析参数", e);
            return R.error("无法解析参数");
        }   catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("查询岗位数据失败", e);
            return R.error("查询数据失败");
        }
    }

    /**
     * 查询岗位信息
     */
//    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除岗位信息")
    @PostMapping("/queryStationByOrgIds")
    public R queryStationByOrgIds(@RequestBody String[] ids) throws Exception {
        try {
            List<Station> stations = stationService.queryStationByOrgIds(Arrays.asList(ids));
            return R.ok().put("stations", stations);
        } catch (Exception e) {
            log.error("无法解析参数", e);
            return R.error("无法解析参数");
        }
    }

    /**
     * 查询模块岗位信息
     */
    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除岗位信息")
    @PostMapping("/queryModuleStationByOrgIds")
    public R queryModuleStationByOrgIds(@RequestBody String[] ids) throws Exception {
        try {
            List<Map<String, Object>> lists = new ArrayList<>();
//            for (String deptId : ids) {
//                Map<String, Object> results = new HashMap<>();
//                Org dept = orgService.selectById(deptId);
//                Org org = orgService.selectById(dept.getParentId());
//                results.put("dept", dept);
//                results.put("org", org);
//
//                List<Station> stations = stationService.queryStationByOrgIds(Arrays.asList(deptId));
//                results.put("stations", stations);
//
//                lists.add(results);
//            }

            for (String deptId : ids) {
                Map<String, Object> results = new HashMap<>();
                Org dept = orgService.selectById(deptId);
                Org org = orgService.selectById(dept.getParentId());
                results.put("deptId", dept.getId());
                results.put("deptName", org.getOrgName() + "-" + org.getOrgName());
                List<Station> stations = stationService.queryStationByOrgIds(Arrays.asList(deptId));
                List<Map<String, Object>> childs = new ArrayList<>();
                for (Station station : stations) {
                    Map<String, Object> child = new HashMap<>();
                    child.put("stationId", station.getId());
                    child.put("stationName", station.getStationName());
                    child.put("moduleType", station.getModuleType());
                    Dictionary dictionary = sysDicService.queryByClassCodeAndDataCode("MODULE", station.getModuleType());
                    child.put("moduleName", dictionary.getDataName());
                    childs.add(child);
                }
                results.put("childs", childs);
                lists.add(results);
            }
            return R.ok().put("lists", lists);
        } catch (Exception e) {
            log.error("无法解析参数", e);
            return R.error("无法解析参数");
        }
    }

    /**
     * 根据id查询岗位信息
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) throws Exception {
        Station councilmbStation = stationService.selectById(id);
        return R.ok().put("station", councilmbStation);
    }

    /**
     * 根据id查询岗位信息
     * @param orgId
     * @return
     * @throws Exception
     */
    @GetMapping("/getStationGroupsByOrgId/{orgId}")
    public R getStationGroupsByOrgId(@PathVariable("orgId") String orgId, HttpServletRequest request) throws Exception {
        String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
        List<Station> stations = stationService.getStationsByOrgId(orgId, moduleType);
        return R.ok().put("stations", stations);
    }

    /**
     * 保存岗位数据
     * @param station
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "save", description = "保存岗位数据信息")
    @PostMapping("/save")
    public R save(@RequestBody Station station) {

        if (station.getId() == null || "".equals(station.getId())) {
            boolean checkStationName = stationService.checkStationName(station.getOrgId(), station.getModuleType(), station.getStationName());
            if (checkStationName) {
                return R.error().put("msg", "岗位名称在当前机构下模块已经存在");
            }
            //新增
            stationService.addStation(station, UserUtil.getUser());
        } else {
            //修改
            stationService.updateStation(station, UserUtil.getUser());
        }
        return R.ok();
    }


    /**
     * 删除岗位信息
     */
    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除岗位信息")
    @PostMapping("/delete")
    public R delete(@RequestBody String[] ids) throws Exception {
        try {
            stationService.deleteBatch(ids);
            return R.ok();
        } catch (Exception e) {
            log.error("删除岗位失败", e);
            return R.error("删除岗位失败");
        }
    }

    /**
     * 批量删除岗位的资源权限
     * @param ids
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "系统功能", methods = "deleteStationRes", description = "批量删除岗位的资源权限", functionNo = "101042")
    @PostMapping("/deleteStationRes")
    public R deleteStationRes(@RequestBody String[] ids) throws Exception {
        try {
            stationService.deleteStationRes(ids, UserUtil.getUser());
            //给日志注解传入业务id
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "deleteStationRes", "bussid", ids.toString(), ids.getClass());
            return R.ok();
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_DELETE.getMsg() + "岗位资源权限" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_DELETE.getMsg() + "岗位资源权限" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 获取树形机构
     * @param tenantId 租户id
     * @return
     * @throws Exception
     */
    @RequestMapping("/treeStationList/{tenantId}")
    @ResponseBody
    public List<TreeUtils> treeStationList(@PathVariable("tenantId") String tenantId) throws Exception {
        return stationService.getAllStationTreeUtilsByTenantId(tenantId);

    }

    /**
     * 获取树形机构，icon属性存的是id
     * @param tenantId 租户id
     * @return
     * @throws Exception
     */
    @RequestMapping("/treeStationListIconFnId/{tenantId}")
    @ResponseBody
    public List<TreeUtils> treeStationListIconFnId(@PathVariable("tenantId") String tenantId) throws Exception {
        return stationService.getAllStationTreeUtilsIconFnIdByTenantId(tenantId);

    }

    /**
     * 根据用户ID获取用户所有岗位信息
     * @param userId
     * @return
     */
    @GetMapping("/getStationDataByUserId/{userId}")
    public R getStationDataByUserId(@PathVariable("userId") String userId) {
        JSONArray jsonArray = stationService.getStationDataByUserId(userId);
        return R.ok().put("stationDataByOrg", jsonArray);
    }


    /**
     *根据组织机构ID和模块类型获取岗位内容
     * @param orgId
     * @param moduleType
     * @return
     */
    @GetMapping("/getStationDataByOrgAndModule/{orgId}/{moduleType}")
    public R getStationDataByOrgAndModule(@PathVariable("orgId") String orgId, @PathVariable("moduleType") String moduleType) {
        Map<String, Object> params = new HashMap<>();
        params.put("moduleType", moduleType);
        params.put("orgId", orgId);
        List<Station> stations = stationService.getStationDataByOrgAndModule(params);
        return R.ok().put("stationData", stations);
    }

    /**
     * 根据所属模块+岗位名称获取岗位下所有用户id
     * @param moduleType,stationName
     * @return
     */
    @GetMapping("/getUserIdListByModuleAndStation/{moduleType}/{stationName}")
    public R getUserIdListByModuleAndStation(@PathVariable("moduleType") String moduleType, @PathVariable("stationName") String stationName) {
        Map<String, Object> params = new HashMap<>();
        params.put("moduleType", moduleType);
        params.put("stationName", stationName);
        List<Map<String, Object>> userIdList = stationService.getUserIdListByModuleAndStation(params);
        return R.ok().put("userIdList", userIdList);
    }

}
